package csu.web.credit_bank.controller;

import csu.web.credit_bank.pojo.Admin;
import csu.web.credit_bank.service.AdminService;
import csu.web.credit_bank.utils.Result;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/admins")
public class AdminController {

    @Autowired
    private AdminService adminService;

    @PostMapping
    public Result<Admin> createAdmin(@RequestBody Admin admin) {
        try {
            return Result.success("管理员创建成功", adminService.createAdmin(admin));
        } catch (Exception e) {
            return Result.failure(e.getMessage());
        }
    }

    @GetMapping("/{userId}")
    public Result<Admin> getAdminById(@PathVariable String userId) {
        Admin admin = adminService.getAdminById(userId);
        return admin != null ? Result.success(admin) : Result.failure("管理员未找到");
    }

    @GetMapping
    public Result<IPage<Admin>> getAdminList(@RequestParam(defaultValue = "1") int page,
                                             @RequestParam(defaultValue = "10") int size) {
        return Result.success(adminService.page(new Page<>(page, size)));
    }

    @PutMapping("/{userId}")
    public Result<Admin> updateAdmin(@PathVariable String userId, @RequestBody Admin admin) {
        admin.setUserId(userId);
        Admin updatedAdmin = adminService.updateAdmin(admin);
        return updatedAdmin != null ? Result.success("管理员更新成功", updatedAdmin) : Result.failure("管理员更新失败");
    }

    @DeleteMapping("/{userId}")
    public Result<Void> deleteAdmin(@PathVariable String userId) {
        return adminService.deleteAdmin(userId) ? Result.success("管理员删除成功") : Result.failure("管理员删除失败");
    }
}
